package cn.mybatishelper.entity.database;

import cn.mybatishelper.common.JdbcUtil;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 数据库实体基类 定义了一张数据库表所应有的一些属性，以及在所需要生成的文件中的对应名称
 *
 * @author GameKing
 */
public class DatabaseEntity {
    /**
     * 所对应的数据库表名
     */
    private String tableName;
    /**
     * 所对应的持久化类名
     */
    private String objectName;
    /**
     * 所对应的持久化类包名
     */
    private String javaPackageName;
    /**
     * 所对应的xml包路径
     */
    private String xmlPackageName;
    /**
     * 库表的各个列的属性
     */
    private List<ColumnEntity> columnList = new ArrayList<ColumnEntity>();

    /**
     * 验证数据库实体是否有效,并以默认规则补完缺失的属性
     */
    public boolean validateAndCompleteEntity() {
        if (StringUtils.isBlank(this.tableName)) {
            return false;
        }
        if (StringUtils.isBlank(this.javaPackageName) || StringUtils.isBlank(xmlPackageName)) {
            return false;
        }
        if (CollectionUtils.isEmpty(columnList)) {
            return false;
        }
        if (StringUtils.isBlank(this.objectName)) {
            completeObjectName();
        }
        return true;
    }

    private void completeObjectName() {
        this.objectName = JdbcUtil.convertTableNameToObjectName(this.tableName);
    }

    /**
     * 获取主键 *
     */
    public ColumnEntity getPrimaryKey() {
        if (CollectionUtils.isEmpty(columnList)) {
            return null;
        }
        for (ColumnEntity entity : columnList) {
            if (entity.isPrimaryKey()) {
                return entity;
            }
        }
        return null;
    }

    /**
     * *********************************** get/set方法 ******************************************
     */
    public String getTableName() {
        return tableName;
    }

    public void setTableName(String tableName) {
        this.tableName = tableName;
    }

    public String getObjectName() {
        return objectName;
    }

    public void setObjectName(String objectName) {
        this.objectName = objectName;
    }

    public List<ColumnEntity> getColumnList() {
        return columnList;
    }

    public void setColumnList(List<ColumnEntity> columnList) {
        this.columnList = columnList;
    }

    public String getJavaPackageName() {
        return javaPackageName;
    }

    public void setJavaPackageName(String javaPackageName) {
        this.javaPackageName = javaPackageName;
    }

    public String getXmlPackageName() {
        return xmlPackageName;
    }

    public void setXmlPackageName(String xmlPackageName) {
        this.xmlPackageName = xmlPackageName;
    }
}
